﻿import QtQuick 2.5
import "./wordcloud.js" as WordCloud

Canvas {
    id: mycanvas
    width:600
    height: 600
    onPaint: {
        var ctx = getContext("2d");
        start(ctx);
    }
    FontMetrics {
        id: fontMetrics
        font.family: "Arial"
    }
    onWidthChanged: {
        requestPaint()
    }
    onHeightChanged: {
        requestPaint();
    }
    function start(ctx){
        var tagCanvas = Qt.rect(mycanvas.x,mycanvas.y,mycanvas.width,mycanvas.height) //document.getElementById('html-canvas');
        var center = WordCloud.getCenterPoint(tagCanvas);
        var cellSpace = 20;
        var maxRadius = WordCloud.getMaxRadius(tagCanvas, cellSpace);
        var data = ["紅樓夢","賈寶玉","林黛玉","薛寶釵","王熙鳳","李紈","賈元春","賈迎春","賈探春","賈惜春","秦可卿","賈巧姐","史湘雲","妙玉","賈政","賈赦","賈璉","賈珍","賈環","賈母","王夫人","薛姨媽","尤氏","平兒","鴛鴦","襲人","晴雯","香菱","紫鵑","麝月","小紅","金釧","甄士隱","賈雨村"];
        var drawArray = [];
        var tempDrawPositionArray = [];

        for(var i =0; i< data.length; i++){
            var dataItem = data[i];
            var textInfo = WordCloud.getTextInfo(dataItem,ctx);
            var drawPosition = null;
            if(i != 0){
                drawPosition = WordCloud.getDrawPosition(textInfo, maxRadius, center, cellSpace, drawArray);
            }
            else{
                textInfo = WordCloud.getTextInfo(dataItem,ctx, {fontSize:60});
                drawPosition = WordCloud.getDrawPosition(
                            textInfo,
                            maxRadius,
                            [center[0]-(textInfo.width/2), center[1]-(textInfo.height/2)],
                            cellSpace,
                            drawArray
                            );
            }

//            if(drawPosition){
//                tempDrawPositionArray.push([drawPosition, textInfo, ctx]);
//            }
            if(drawPosition){
                WordCloud.drawText(drawPosition, textInfo, ctx);
            }
        }
//        for(var ii=tempDrawPositionArray.length-1;ii>=0;ii--){
//            var textItem = tempDrawPositionArray.shift();
//            //console.log("left size of array:",tempDrawPositionArray.length);
//            if(textItem){
//                WordCloud.drawText(textItem[0], textItem[1], textItem[2]);
//            }
//        }
    }
}
